//引入express模块
const express = require("express");
//引入数据池对象
const pool = require("../pool.js");
//创建路由器对象
const r = express.Router();

//第三方验证码架包
const svgCaptcha = require('svg-captcha');
r.get("/code",(req,res)=>{
	//数字验证码
	const cap = svgCaptcha.createMathExpr({
		fontSize: 45,
		mathMin:1,
		mathMax:9,
		mathOperator:"+-",
		width: 110,
	    height: 45,
		color:true,
	})	
	req.session.captcha = cap.text;
	res.type("svg");
	res.send(cap.data)
});

//1.用户注册
r.post("/ref",(req,res)=>{
	var obj=req.body;
	var sql="INSERT INTO dd_user (id,uname,upwd) VALUES(null,?,?)"; 
	console.log(obj);
	pool.query(sql,[obj.uname,obj.upwd],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows>0){
			res.send("1");
		}else{
			res.send("0");
		}
	});
});
//2.判断用户名是否存在
r.get("/isexists",(req,res)=>{
	var obj=req.query;
	var sql="SELECT id FROM dd_user WHERE uname = ?"; 
	console.log(sql,obj);
	pool.query(sql,[obj.uname],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send("1");
		}else{
			res.send("0");
		}
	});
});
//3.用户登录
r.get("/login/:uname&:upwd",(req,res)=>{
	var uname =req.params.uname;
	var upwd =req.params.upwd;
	var sql="select * from dd_user where uname=? and upwd=?";
	pool.query(sql,[uname,upwd],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send("1");
		}else{
			res.send("0");
		}
	});
});
//4.查询用户列表   
r.get("/list",(req,res)=>{
	var sql="select * from dd_user";
	pool.query(sql,(err,result)=>{
		if(err) throw err;
		res.send(result);
	});
});

//5.根据删除用户
r.delete("/delUser/:id",(req,res)=>{
	var id=req.params.id;
	var sql="delete from dd_user where id=?";
	pool.query(sql,[id],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows>0){
			res.send({code:1,msg:"删除成功"});
		}else{
			res.send({code:1,msg:"删除失败"});
		}
	});
});
//6.根据id修改用户信息
r.put("/update",(req,res)=>{
	var obj=req.body;
	var sql="update dd_user set email = ? where id=?"; 
	console.log(sql,obj);
	pool.query(sql,[obj.email,obj.id],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows>0){
			res.send("1");
		}else{
			res.send("0");
		}
	});
});

//导出路由对象
module.exports = r;